from rest_framework import serializers

from users.models import User
from .models import OAuthQQUser
from django_redis import get_redis_connection


class QQRegisterSerializer(serializers.Serializer):
    """
     创建QQ关联数据和用户模型数据
     """

    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)

    def validate(self, attrs):
        # 获取token中的openid
        access_token = attrs.get('access_token')
        openid = OAuthQQUser.check_save_user_token(access_token)

        if not openid:
            raise serializers.ValidationError('token无效')

        attrs['openid'] = openid
        # 校验短信验证码
        mobile = attrs.get('mobile')
        redis_conn = get_redis_connection('code')
        # 获取短信验证码
        redis_sms = redis_conn.get('sms_%s' % mobile)
        if not redis_sms:
            raise serializers.ValidationError('短信验证码获取失败')

        # 校验短信内同
        if attrs['sms_code'] != redis_sms.decode():
            raise serializers.ValidationError('短信验证码错误!')

        # 获取用户
        try:
            user = User.objects.get(mobile=mobile)
        except Exception:
            user = None
        else:
            # 校验密码
            pwd = attrs['password']
            if not user.check_password(pwd):
                raise serializers.ValidationError('密码错误')

            attrs['user'] = user
        return attrs

    def create(self, validated_data):
        # 获取用户
        user = validated_data.get('user')

        # 用户不存在就新增
        if not user:
            user = User.objects.create(
                username=validated_data.get('mobile'),
                password=validated_data.get('password'),
                mobile=validated_data.get('mobile')
            )
            # 修改密码
            user.set_password(validated_data['password'])
            user.save()

        # 保存用户 到 qq绑定表中
        OAuthQQUser.objects.create(
            openid=validated_data.get('openid'),
            user=user
        )

        return user
